package chat.join;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import pojo.User;
import utils.ServerConfig;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//加入服务器
public class Join {
    private User user;

    public Join(User user) {
        this.user = user;
    }

    public int run() {
        Socket socket=null;
        OutputStream outputStream=null;
        InputStream inputStream=null;
        ByteOutputStream byteOutputStream=null;
        try {
            //连接服务器端口
            socket = new Socket(InetAddress.getByName(ServerConfig.serverConfigString("InetAddress")),ServerConfig.serverConfig("ServerJoinPort"));
            outputStream = socket.getOutputStream();
            //向服务器发送用户信息
            outputStream.write(user.getName().getBytes(StandardCharsets.UTF_8));
            //发送结束
            socket.shutdownOutput();

            //准备接收服务器信息
            inputStream = socket.getInputStream();
            byteOutputStream = new ByteOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while((len=inputStream.read(bytes))!=-1){
                byteOutputStream.write(bytes);
            }
            byteOutputStream.close();
            inputStream.close();
            outputStream.close();
            //接收信息，判断是否已经加入成功
            System.out.println(Integer.parseInt(byteOutputStream.toString().trim()));
            return Integer.parseInt(byteOutputStream.toString().trim());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            byteOutputStream.close();
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        try {
//            DatagramSocket socket = new DatagramSocket();
//            DatagramPacket packet = new DatagramPacket(user.getName().getBytes(StandardCharsets.UTF_8),0,user.getName().getBytes(StandardCharsets.UTF_8).length,
//                    InetAddress.getByName(ServerConfig.serverConfigString("InetAddress")),ServerConfig.serverConfig("ServerJoinPort"));
//            socket.send(packet);
//            socket.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return 0;
    }

}
